<script setup lang="ts">
import { reactive, ref } from "vue";
import { KnowledgeList, KnowledgeParams, KnowledgeType } from "@/types/homeTypes";
import KnowledgeItem from "@/views/home/components/knowledgeList/knowledgeItem.vue";
import { fetchKnowledgeListAPI } from "@/api/homeApi.ts";
import { showFailToast } from "vant";

const props = defineProps<{
    type: KnowledgeType
}>();

/*获取首页文章知识列表的参数*/
const params = reactive<KnowledgeParams>({
    type: props.type,
    current: 1,
    pageSize: 10,
});

/*文章知识列表*/
const knowledgeList = ref<KnowledgeList>([]);
/*文章知识列表总数据条数*/
const total = ref(0);
/*是否处于加载中*/
const loading = ref(false);
/*是否加载完毕*/
const finished = ref(false);
/*下拉刷新是否加载完成*/
const refreshLoading = ref(false);
/*滚动条与底部距离小于offset时触发*/
const onLoad = async () => {
    try {
        const { data } = await fetchKnowledgeListAPI(params);
        total.value = data.total;
        knowledgeList.value.push(...data.rows);
        if (knowledgeList.value.length >= total.value) {
            finished.value = true;
        } else {
            params.current++;
        }
        loading.value = false;
    } catch (error: any) {
        showFailToast(error.message);
    }
};

/*下拉刷新时触发*/
const onRefresh = async () => {
    params.current=1
    params.pageSize=10
    knowledgeList.value=[]
    finished.value=false
    await onLoad()
    refreshLoading.value=false
};
</script>

<template>
    <div class="knowledge-list">
        <van-pull-refresh v-model="refreshLoading" @refresh="onRefresh"  success-text="刷新成功">
            <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多数据了" @load="onLoad">
                <knowledge-item v-for="(item) in knowledgeList" :key="item.id" :item="item"></knowledge-item>
            </van-list>
        </van-pull-refresh>
        <van-back-top :offset="500" bottom="80px"></van-back-top>
    </div>
</template>

<style scoped lang="scss">
.knowledge-list {
    padding: 0 15px;
}
</style>
